package com.test19_多线程;

public class Demo10_Other {

    public static void main(String[] args) throws Exception {
//        test1();
//        test2();
        test3();
    }

    /**
     * 优雅的停止线程
     */
    public static void test1() throws Exception {
        Message2 message = new Message2();
        new Thread(message).start();
        Thread.sleep(2000);     // 让线程先运行2秒的时间
        message.stop();
    }

    /**
     * 守护线程
     */
    public static void test2() {
        Message3 message = new Message3();
        new Thread(message).start();
    }

    /**
     * volatile关键字
     * 作用：不再进行副本的定义，直接操作主内存中的变量
     * volatile避免了各种变量的拷贝以及重新同步所带来的的延迟损耗，而可以直接进行更加快速的主内存变量访问
     */
    public static void test3() {
        TicketThread threadBody = new TicketThread();
        new Thread(threadBody, "票贩子-A").start();
        new Thread(threadBody, "票贩子-B").start();
        new Thread(threadBody, "票贩子-C").start();
    }
}

class Message2 implements Runnable {
    private boolean stopFlag = false;   // 停止标记

    @Override
    public void run() {
        for (int x = 0; x < 1000; x++) {
            if (this.stopFlag) {
                break;  // 退出循环
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("【Message信息输出 - " + x + "】沐言科技：www.yootk.com");
        }
    }

    public void stop() {
        this.stopFlag = true;
    }
}

class Message3 implements Runnable {

    public Message3() {
        Thread daemonThread = new Thread(() -> {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("【守护线程】李兴华编程训练营：yootk.ke.qq.com");
        });
        daemonThread.setDaemon(true);   // 设置为守护线程
        daemonThread.start();   // 守护线程启动
    }

    @Override
    public void run() {
        for (int x = 0; x < 10; x++) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("【Message信息输出 - " + x + "】沐言科技：www.yootk.com");
        }
    }
}

class TicketThread implements Runnable {
    private volatile int ticket = 3;    // 总票数

    @Override
    public void run() {
        while (true) {
            this.sale();
        }
    }

    public synchronized boolean sale() {
        if (this.ticket > 0) {  // 有票就买
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("【" + Thread.currentThread().getName() + "】售票，剩余票数为，ticket = " + (--this.ticket));
            return true;
        }
        return false;
    }
}
